package com.youlai.netty.service.tcp.server;

import com.youlai.netty.service.handler.MQTTHandler;
import com.youlai.netty.service.handler.WebSocketHandler;
import com.youlai.netty.service.tcp.BootNettyChannelInboundHandlerAdapter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author zc
 * @date 2023-02-04 20:19
 */
@Slf4j
public class WebSocketServer {

    public void bind(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        protected void initChannel(NioSocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            //1.Netty提供的针对Http的编解码
                            pipeline.addLast(new HttpServerCodec());

                            //是以块方式写，添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());

                            //http数据在传输过程中是分段, HttpObjectAggregator ，就是可以将多个段聚合
                            pipeline.addLast(new HttpObjectAggregator(8192));

                            //将 http协议升级为 ws协议 , 保持长连接
                            pipeline.addLast(new WebSocketServerProtocolHandler("/"));

                            //2.自定义处理WebSocket的业务Handler
                            pipeline.addLast(new WebSocketHandler());
                        }
                    });
            ChannelFuture f = serverBootstrap.bind(port).sync();
            if(f.isSuccess()){
                log.info("WebSocket服务启动成功,端口:{}",port);
                /**
                 * 等待服务器监听端口关闭
                 */
                f.channel().closeFuture().sync();
            }else{
                serverBootstrap.config().group().schedule(new Runnable() {
                    @Override
                    public void run() {
                        bind(port);
                    }
                },5, TimeUnit.SECONDS);
                log.error("创建WebSocket服务失败:{}",f.cause().getMessage());
            }
        } catch (InterruptedException e) {
            log.warn("创建WebSocketServer异常:{}",e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
